package cn.cjxy.userms.controller;

import cn.cjxy.userms.entity.User;
import cn.cjxy.userms.service.UserService;
import cn.cjxy.userms.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    UserService userService=new UserServiceImpl();
    //
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.接收前端传递的参数
        String username = req.getParameter("username");//用户名
        String password = req.getParameter("password");//密码
        String checkCode = req.getParameter("checkCode");//验证码

        //对比验证码
        //先从服务器中得到session  再用session获取服务器上的验证码
        HttpSession session = req.getSession();
        //服务器端的验证码
        String safeCode = (String) session.getAttribute("safeCode");
        //比对用户端的验证码和服务器端的验证码
        if (!checkCode.equalsIgnoreCase(safeCode)){
            //验证码有误
            //告诉他错了
            req.setAttribute("error","验证码有误，请重新输入！");
            //回到登录页
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
        }
        //下面就是验证码正确的情况
        //2.调用业务层进行业务处理
        User loginUser = userService.login(username, password);
        //3.根据业务层返回的结果来决定跳转到哪个视图
        if (loginUser == null){
                //说明没查到
                //前端提示
                req.setAttribute("error","用户名或密码错误！");
                //回到登录页
                req.getRequestDispatcher("/login.jsp").forward(req, resp);
        }
        //下边就是查到的情况
        //将用户的信息存入作用域
        session.setAttribute("loginUser",loginUser);
        //进入列表页
        resp.sendRedirect("/list");

    }
}
